import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../config/app_colors.dart';

class JoyForgotPasswordPage extends StatefulWidget {
  const JoyForgotPasswordPage({super.key});

  @override
  State<JoyForgotPasswordPage> createState() => _JoyForgotPasswordPageState();
}

class _JoyForgotPasswordPageState extends State<JoyForgotPasswordPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _verificationCodeController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();
  
  bool _obscureNewPassword = true;
  bool _obscureConfirmPassword = true;
  int _countdown = 0;
  bool _isCountingDown = false;

  @override
  void dispose() {
    _emailController.dispose();
    _verificationCodeController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  // 获取验证码
  void _getVerificationCode() {
    if (_emailController.text.trim().isEmpty) {
      _showSnackBar('Please enter your email address');
      return;
    }
    
    // 验证邮箱格式
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegex.hasMatch(_emailController.text.trim())) {
      _showSnackBar('Please enter a valid email address');
      return;
    }

    // 开始倒计时
    setState(() {
      _countdown = 60;
      _isCountingDown = true;
    });

    // 倒计时逻辑
    Future.doWhile(() async {
      await Future.delayed(Duration(seconds: 1));
      if (_countdown > 0 && mounted) {
        setState(() {
          _countdown--;
        });
        return true;
      } else {
        if (mounted) {
          setState(() {
            _isCountingDown = false;
          });
        }
        return false;
      }
    });

    // TODO: 调用API发送验证码
    _showSnackBar('Verification code sent to ${_emailController.text}');
  }

  // 重置密码
  void _resetPassword() {
    // 验证所有输入
    if (_emailController.text.trim().isEmpty) {
      _showSnackBar('Please enter your email address');
      return;
    }
    
    if (_verificationCodeController.text.trim().isEmpty) {
      _showSnackBar('Please enter verification code');
      return;
    }
    
    if (_newPasswordController.text.trim().isEmpty) {
      _showSnackBar('Please enter new password');
      return;
    }
    
    if (_confirmPasswordController.text.trim().isEmpty) {
      _showSnackBar('Please confirm your password');
      return;
    }
    
    if (_newPasswordController.text != _confirmPasswordController.text) {
      _showSnackBar('Passwords do not match');
      return;
    }

    // TODO: 调用API重置密码
    // loginBloc.add(ResetPasswordEvent(
    //   context,
    //   _emailController.text,
    //   _verificationCodeController.text,
    //   _newPasswordController.text,
    // ));

    Get.back();
    _showSnackBar('Password reset successful! Please log in with your new password.');
  }

  // 显示提示消息
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppColors.primaryVariant,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.backHomeYellowGround,
        title: Text(
          'Forgot Password',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        leading: GestureDetector(
          onTap: () => Get.back(),
          child: Container(
            margin: EdgeInsets.only(left: 10,right: 10,top: 10,bottom: 10),
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: AppColors.primaryVariant,
              size: 18.sp,
            ),
          ),
        ),
      ),
      backgroundColor: const Color(0xFFF8F9FA),
      body: SafeArea(
        child: Column(
          children: [
            // 自定义AppBar
          //  _buildAppBar(),
            
            // 主要内容区域
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(24.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 顶部图标
                    Center(
                      child: Container(
                        width: 80.w,
                        height: 80.w,
                        decoration: BoxDecoration(
                          color: AppColors.primaryVariant.withOpacity(0.1),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.lock_reset,
                          size: 40.sp,
                          color: AppColors.primaryVariant,
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                    
                    // 标题和说明
                    Center(
                      child: Text(
                        'Forgot Password',
                        style: TextStyle(
                          fontSize: 24.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    SizedBox(height: 12.h),
                    
                    Center(
                      child: Text(
                        'Enter your email address and we will send you\na verification code to reset your password.',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[600],
                          height: 1.5,
                        ),
                      ),
                    ),
                    SizedBox(height: 32.h),
                    
                    // 邮箱输入框
                    _buildInputLabel('Email Address'),
                    SizedBox(height: 8.h),
                    _buildTextField(
                      controller: _emailController,
                      hintText: 'Enter your email',
                      prefixIcon: Icons.email_outlined,
                      keyboardType: TextInputType.emailAddress,
                    ),
                    SizedBox(height: 20.h),
                    
                    // 验证码输入框和获取按钮
                    _buildInputLabel('Verification Code'),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Expanded(
                          child: _buildTextField(
                            controller: _verificationCodeController,
                            hintText: 'Enter code',
                            prefixIcon: Icons.verified_user_outlined,
                            keyboardType: TextInputType.number,
                            maxLength: 6,
                          ),
                        ),
                        SizedBox(width: 12.w),
                        ElevatedButton(
                          onPressed: _isCountingDown ? null : _getVerificationCode,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _isCountingDown 
                                ? Colors.grey[300] 
                                : AppColors.primaryVariant,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 20.w,
                              vertical: 14.h,
                            ),
                            elevation: 0,
                            minimumSize: Size(100.w, 50.h),
                          ),
                          child: Text(
                            _isCountingDown ? '${_countdown}s' : 'Get Code',
                            style: TextStyle(
                              color: _isCountingDown ? Colors.grey[600] : Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.h),
                    
                    // 新密码输入框
                    _buildInputLabel('New Password'),
                    SizedBox(height: 8.h),
                    _buildPasswordTextField(
                      controller: _newPasswordController,
                      hintText: 'Enter new password',
                      obscureText: _obscureNewPassword,
                      onToggleVisibility: () {
                        setState(() {
                          _obscureNewPassword = !_obscureNewPassword;
                        });
                      },
                    ),
                    SizedBox(height: 20.h),
                    
                    // 确认密码输入框
                    _buildInputLabel('Confirm Password'),
                    SizedBox(height: 8.h),
                    _buildPasswordTextField(
                      controller: _confirmPasswordController,
                      hintText: 'Confirm new password',
                      obscureText: _obscureConfirmPassword,
                      onToggleVisibility: () {
                        setState(() {
                          _obscureConfirmPassword = !_obscureConfirmPassword;
                        });
                      },
                    ),
                    SizedBox(height: 32.h),
                    
                    // 重置密码按钮
                    SizedBox(
                      width: double.infinity,
                      height: 50.h,
                      child: ElevatedButton(
                        onPressed: _resetPassword,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColors.primaryVariant,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          elevation: 2,
                          shadowColor: AppColors.primaryVariant.withOpacity(0.3),
                        ),
                        child: Text(
                          'Reset Password',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 20.h),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建AppBar
  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 8,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: AppColors.primaryVariant,
                size: 18.sp,
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Forgot Password',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ),
          ),
          SizedBox(width: 40.w), // 占位，保持标题居中
        ],
      ),
    );
  }

  // 构建输入标签
  Widget _buildInputLabel(String label) {
    return Text(
      label,
      style: TextStyle(
        fontSize: 14.sp,
        color: Colors.black87,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  // 构建普通输入框
  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    required IconData prefixIcon,
    TextInputType? keyboardType,
    int? maxLength,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey[300]!),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        controller: controller,
        keyboardType: keyboardType,
        maxLength: maxLength,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            color: Colors.grey[400],
            fontSize: 14.sp,
          ),
          prefixIcon: Icon(
            prefixIcon,
            color: AppColors.primaryVariant,
            size: 22.sp,
          ),
          border: InputBorder.none,
          counterText: '',
          contentPadding: EdgeInsets.symmetric(
            horizontal: 16.w,
            vertical: 14.h,
          ),
        ),
      ),
    );
  }

  // 构建密码输入框
  Widget _buildPasswordTextField({
    required TextEditingController controller,
    required String hintText,
    required bool obscureText,
    required VoidCallback onToggleVisibility,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey[300]!),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            color: Colors.grey[400],
            fontSize: 14.sp,
          ),
          prefixIcon: Icon(
            Icons.lock_outline,
            color: AppColors.primaryVariant,
            size: 22.sp,
          ),
          suffixIcon: GestureDetector(
            onTap: onToggleVisibility,
            child: Icon(
              obscureText ? Icons.visibility_off : Icons.visibility,
              color: Colors.grey[500],
              size: 22.sp,
            ),
          ),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 16.w,
            vertical: 14.h,
          ),
        ),
      ),
    );
  }
}
